<?php
namespace app\common\loglic;

use app\common\loglic\Update;

class Update16 extends Update
{
    private $version = '1.6.0';
    
    //框架升级脚本
    public function upgrade()
    {
        if(is_file('./datas/db/'.$this->version.'.lock')){
			$this->error = '已经是最新版，建议删除该文件（./apps/common/loglic/Update16.php）';
            return false;
		}
        
        //升级表结构	
		if(config('database.type') == 'sqlite'){
            $this->_sqlite();
        }else{
            $this->_mysql();
        }
        
        //迁移数据
        if(config('database.type') == 'mysql'){
            $this->_mysqlData();
        }else{
            $this->_sqliteData();
        }
        
        touch('./datas/db/'.$this->version.'.lock');
        
        $this->deleteFiles();
        
        $this->configClear();
        
        return true;
    }
    
    private function _mysql()
    {
        //数库库结构信息
        $tables = $this->tablesInfo();
        
        //数据库前缀 修改term_map表字段
        $prefix = config('database.prefix');
        
        //定义变量
        $sql = [];
        
        //term表字段
        $fields = array_flip($tables['fields'][$prefix.'term']);
        if( !isset($fields['term_type']) ){
            array_push($sql, "ALTER TABLE ".$prefix."term Add term_type VARCHAR(100) NULL AFTER `term_order`;");
        }
        if( !isset($fields['term_info']) ){
            array_push($sql, "ALTER TABLE ".$prefix."term Add term_info TEXT NULL AFTER `term_type`;");
        }
        if( !isset($fields['term_parent']) ){
            array_push($sql, "ALTER TABLE ".$prefix."term Add term_parent BIGINT(20) NOT NULL DEFAULT '0' AFTER `term_info`;");
        }
        if( !isset($fields['term_count']) ){
            array_push($sql, "ALTER TABLE ".$prefix."term Add term_count INT(11) NOT NULL DEFAULT '0' AFTER `term_parent`;");
        }
        if( !isset($fields['term_controll']) ){
            array_push($sql, "ALTER TABLE ".$prefix."term Add term_controll VARCHAR(100) NULL AFTER `term_module`;");
        }
        if( !isset($fields['term_action']) ){
            array_push($sql, "ALTER TABLE ".$prefix."term Add term_action VARCHAR(100) NULL AFTER `term_controll`;");
        }
        //term表索引
        $index = array_flip($tables['index'][$prefix.'term']);
        //增加索引
        if( !isset($index['term_type']) ){
            array_push($sql,"CREATE INDEX term_type ON ".$prefix."term(term_type);");//增加索引
        }
        if( !isset($index['term_parent']) ){
            array_push($sql,"CREATE INDEX term_parent ON ".$prefix."term(term_parent);");//增加索引
        }
        if( !isset($index['term_module']) ){
            array_push($sql,"CREATE INDEX term_module ON ".$prefix."term(term_module);");
        }
        if( !isset($index['term_controll']) ){
            array_push($sql,"CREATE INDEX term_controll ON ".$prefix."term(term_controll);");//增加索引
        }
        if( !isset($index['term_action']) ){
            array_push($sql,"CREATE INDEX term_action ON ".$prefix."term(term_action);");//增加索引
        }
        
        //term_map表字段
        $fields = array_flip($tables['fields'][$prefix.'term_map']);
        if( isset($fields['term_much_id']) ){
            array_push($sql,"ALTER TABLE `".$prefix."term_map` CHANGE `term_much_id` `term_id` BIGINT(20) NULL DEFAULT '0';");
        }
        //term_map表索引
        $index = array_flip($tables['index'][$prefix.'term_map']);
        //增加索引
        if( !isset($index['map_term_id']) ){
            array_push($sql,"CREATE INDEX map_term_id ON ".$prefix."term_map(term_id);");
        }
        if( !isset($index['map_info_id']) ){
            array_push($sql,"CREATE INDEX map_info_id ON ".$prefix."term_map(detail_id);");
        }
        //删除索引
        if( isset($index['term_much_id']) ){
            array_push($sql,"DROP INDEX term_much_id ON ".$prefix."term_map;");
        }
        if( isset($index['detail_id']) ){
            array_push($sql,"DROP INDEX detail_id ON ".$prefix."term_map;");
        }
        
        //执行SQL语句
        //dump($sql);
        $this->executeSql($sql);
    }
    private function _mysqlData()
    {
        //迁移旧数据与新增数据等
        $this->dataUpdate();
        
        //数据库前缀 修改term_map表字段
        $prefix = config('database.prefix');
        
        //SQL语句变量
        $sql = [];
        
        //删除废弃表
        array_push($sql,"DROP TABLE IF EXISTS `".$prefix."term_much`;");
        
        //执行SQL语句
        //dump($sql);
        $this->executeSql($sql);
    }
    
    private function _sqlite()
    {
        
        //数库库结构信息
        $tables = $this->tablesInfo();
        
        //数据库前缀 修改term_map表字段
        $prefix = config('database.prefix');
        
        //定义变量
        $sql = [];
        
        //term表字段（增加字段）
        $fields = array_flip($tables['fields'][$prefix.'term']);
        if( !isset($fields['term_type']) ){
            array_push($sql, "ALTER TABLE ".$prefix."term Add term_type VARCHAR(100) NULL;");
        }
        if( !isset($fields['term_info']) ){
            array_push($sql, "ALTER TABLE ".$prefix."term Add term_info TEXT NULL;");
        }
        if( !isset($fields['term_parent']) ){
            array_push($sql, "ALTER TABLE ".$prefix."term Add term_parent INTEGER DEFAULT '0' NULL;");
        }
        if( !isset($fields['term_count']) ){
            array_push($sql, "ALTER TABLE ".$prefix."term Add term_count INTEGER DEFAULT '0' NULL;");
        }
        if( !isset($fields['term_controll']) ){
            array_push($sql, "ALTER TABLE ".$prefix."term Add term_controll VARCHAR(100) NULL;");
        }
        if( !isset($fields['term_action']) ){
            array_push($sql, "ALTER TABLE ".$prefix."term Add term_action VARCHAR(100) NULL;");
        }
        //term表索引(新增索引)
        $index = array_flip($tables['index'][$prefix.'term']);
        if( !isset($index['term_type']) ){
            array_push($sql, "CREATE INDEX term_type ON [".$prefix."term](term_type ASC);");
        }
        if( !isset($index['term_parent']) ){
            array_push($sql, "CREATE INDEX term_parent ON [".$prefix."term](term_parent ASC);");
        }
        if( !isset($index['term_module']) ){
            array_push($sql, "CREATE INDEX term_module ON [".$prefix."term](term_module ASC);");
        }
        if( !isset($index['term_controll']) ){
            array_push($sql, "CREATE INDEX term_controll ON [".$prefix."term](term_controll ASC);");
        }
        if( !isset($index['term_action']) ){
            array_push($sql, "CREATE INDEX term_action ON [".$prefix."term](term_action ASC);");
        }
        
        //term_map表索引（删除不需要的索引）
        $index = array_flip($tables['index'][$prefix.'term_map']);
        if( isset($index['term_much_id']) ){
            array_push($sql,"DROP INDEX term_much_id;");
        }
        if( isset($index['detail_id']) ){
            array_push($sql,"DROP INDEX detail_id;");
        }
        
        //term_map表（修改字段类型）
        $fields = array_flip($tables['fields'][$prefix.'term_map']);
        if( isset($fields['term_much_id']) ){
            array_push($sql, "ALTER TABLE ".$prefix."term_map RENAME TO temp_term_map;");//把原表改成暂存表
            array_push($sql, "CREATE TABLE ".$prefix."term_map(detail_id INTEGER DEFAULT '0' NULL, term_id INTEGER DEFAULT '0' NULL);");//建新表
            array_push($sql, "INSERT INTO ".$prefix."term_map SELECT * FROM temp_term_map;");//将暂存表数据写入到新表
            array_push($sql, "DROP TABLE temp_term_map;");//删除暂存表
            //array_push($sql, "CREATE TABLE newTb as select * from oldTb;");//复制表结构与数据
        }
        //term_map表索引（增加索引）
        $index = array_flip($tables['index'][$prefix.'term_map']);
        if( !isset($index['map_term_id']) ){
            array_push($sql,"CREATE INDEX map_term_id ON [".$prefix."term_map](term_id);");
        }
        if( !isset($index['map_info_id']) ){
            array_push($sql,"CREATE INDEX map_info_id ON [".$prefix."term_map](detail_id);");
        }
        
        //执行升级语句
        //dump($sql);
        $this->executeSql($sql);
    }
    private function _sqliteData()
    {
        //迁移旧数据与新增数据等
        $this->dataUpdate();
        
        //数据库结构信息
        $tables = $this->tablesInfo();
        
        //数据库前缀
        $prefix = config('database.prefix');
        
        //SQL语句变量
        $sql = [];
        
        //term_much表（先删除索引）
        $index = array_flip($tables['index'][$prefix.'term_much']);
        if( isset($index['term_id_index']) ){
            array_push($sql, "DROP INDEX term_id_index;");
        }
        if( isset($index['term_much_type']) ){
            array_push($sql, "DROP INDEX term_much_type;");
        }
        //term_much（删除废弃的表）
        if($tables['fields'][$prefix.'term_much']){
            array_push($sql, "DROP TABLE ".$prefix."term_much;");
        }
        //执行升级语句
        //dump($sql);
        $this->executeSql($sql);
    }
    
    //默认数据处理
    private function dataUpdate()
    {
        //旧表不存在直接退出
        $fieldsTermMuch = $this->getTableInfo(config('database.prefix').'term_much','fields');
        if(!$fieldsTermMuch){
            return false;
        }
        //迁移分类表旧数据
        $data = [];
        foreach(db('term_much')->select() as $key=>$value){
            $data[$key]['term_id']     = $value['term_id'];
            $data[$key]['term_type']   = $value['term_much_type'];
            $data[$key]['term_info']   = $value['term_much_info'];
            $data[$key]['term_parent'] = DcEmpty($value['term_much_parent'],0);
            $data[$key]['term_count']  = $value['term_much_count'];
        }
        //批量添加旧数据
        $result = model('common/Term')->isUpdate()->saveAll($data);
        //dump(DcArrayResult($result));
        //返回结果
        return true;
    }
    
    //删除旧文件
    private function deleteFiles()
    {
        $file = new \files\File();
        //删除文件
        $file->f_delete('./apps/admin/controller/Hook.php');
        $file->f_delete('./apps/admin/controller/Nav.php');
        $file->f_delete('./apps/api/tags.php');
        $file->f_delete('./apps/common/event/Apply.php');
        $file->f_delete('./apps/common/event/Hook.php');
        $file->f_delete('./apps/common/event/Op.php');
        $file->f_delete('./apps/common/event/Route.php');
        $file->f_delete('./apps/common/model/TermMuch.php');
        $file->f_delete('./apps/common/validate/Nav.php');
        $file->f_delete('./apps/common/validate/TermMuch.php');
        $file->f_delete('./apps/index/tags.php');
        $file->f_delete('./extend/daicuo/Hook.php');
        $file->f_delete('./extend/daicuo/Nav.php');
        $file->f_delete('./extend/daicuo/Version.php');
        //删除目录
        $file->d_delete('./apps/admin/view/hook/');
        $file->d_delete('./apps/admin/view/nav/');
    }
    
    //清空缓存
    private function configClear()
    {
        $file = new \files\File();
        
        $file->d_delete(LOG_PATH);
        
        $file->d_delete(CACHE_PATH);
        
        $file->d_delete(TEMP_PATH);
    }
}